<template>
  <div id="change-record" v-title data-title="项目变更页面">
    <div class="container"  ref="imageWrapper">
      <div class="content">
        <div class="tip-head"></div>
        <div class="content-title">
          <div class="header">
            <span><strong>项目编号：</strong>{{ projectBuildData.projectNo }}</span>
            <span><strong>项目名称：</strong>{{ projectBuildData.projectName }}</span>
            <span id="projectChangeNo"><strong>变更单号：</strong>{{ projectChangeData.projectChangeNo }}</span>
          </div>
          <div>
            <a-button style="margin-right: 20px" @click="projectReserve" v-if="reserveBtnShow">
              <a-icon type="select" />转储备
            </a-button>
            <a-button style="margin-right: 20px" type="primary" @click="showHistoryList = true">
              <a-icon type="ordered-list" />变更历史记录
            </a-button>
            <a-button  @click="print" v-show="showPrintBtn">
              打印
            </a-button>
          </div>
        </div>
        <div class="content-container">
          <h4>变更单信息</h4>
          <a-form-model ref="ruleForm" :model="projectChangeData" :rules="rules">
            <a-row class="line-content">
              <a-col :span="8" class="dept">
                <a-form-model-item
                  label="项目变更主要责任部门"
                  prop="dutyDeptName"
                  labelAlign="left"
                  :labelCol="{ span: 9 }"
                  :wrapperCol="{ span: 11 }"
                >
                  <a-input
                    placeholder="请输入部门名称"
                    v-model="projectChangeData.dutyDeptName"
                    :disabled="projectChangeData.status && projectChangeData.status != '1'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="主要负责人"
                  prop="dutyUserName"
                  :labelCol="{ span: 8 }"
                  :wrapperCol="{ span: 14 }"
                >
                  <a-input
                    placeholder="请选择主要责任人"
                    readOnly
                    v-model="projectChangeData.dutyUserName"
                    :disabled="projectChangeData.status && projectChangeData.status != '1'"
                    @click="selectDutyUser()"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="变更类型"
                  prop="changeType"
                  :labelCol="{ span: 9 }"
                  :wrapperCol="{ span: 15 }"
                >
                  <a-select
                    v-model="projectChangeData.changeType"
                    placeholder="请选择变更类型"
                    :options="changeTypeOptions"
                    :disabled="projectChangeData.status && projectChangeData.status != '1'"
                  >
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-icon type="menu-unfold" style="margin-right: 5px" /><span style="font-weight: bolder"
                >预算变更内容</span
              >
              <a-form-model-item prop="budgetChangeContent">
                <a-checkbox-group
                  v-model="budgetChangeContentList"
                  :options="budgetChangeContentOptions"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                  @change="changeBudgetChangeContentList"
                />
              </a-form-model-item>
            </a-row>
            <a-row v-if="budgetChangeContentList.length > 0">
              <a-icon type="menu-unfold" style="margin-right: 5px" /><span style="font-weight: bolder">变更说明</span>
              <div style="margin-bottom: 20px">
                本次变更费用为不含税￥<a-input
                  placeholder="必填，输入数字"
                  style="border-color: red; width: 130px; text-align: right; margin: 0 2px"
                  v-model="projectChangeData.changeTotal"
                  @blur="checkInputMoney"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                />元， 需追加至SAP系统费用不含税￥<a-input
                  placeholder="必填，输入数字"
                  style="border-color: red; width: 130px; text-align: right; margin: 0 2px"
                  v-model="projectChangeData.addToSapTotal"
                  @blur="checkInputMoney"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                />元
              </div>
            </a-row>
            <a-row v-if="budgetChangeContentList.length > 0">
              <a-icon type="menu-unfold" style="margin-right: 1px" /><span style="font-weight: bolder">预算项变更</span>
              <span style="color: red">（单位：元(不含税)）</span>
              <a-button
                type="primary"
                style="width: 80px; margin-right: 15px; margin-left: 15px"
                @click="addFactory"
                v-if="btnShow"
                >添加</a-button
              >
              <a-button style="width: 80px; margin-right: 15px" @click="delBudgetItem" v-if="btnShow">删除</a-button>
              <a-button style="margin-right: 15px" @click="changeCostCenter" v-if="btnShow">修改成本中心号</a-button>
              <span class="infoTips">
                <a-icon type="exclamation-circle" theme="filled" style="color: #47a4fa" />
                注意：各分项费用之和需等于追加SAP系统费用，费用减少则填写负值。
              </span>
              <!--<a-table
                v-if="budgetGroups && budgetGroups.length > 0"
                :scroll="{ x: true }"
                :columns="budgetGroupColumns"
                :data-source="budgetGroups"
                bordered
                rowKey="factoryCode"
                :defaultExpandAllRows="true"
                :pagination="false"
                style="margin-top: 5px; margin-bottom: 5px"
                :row-selection="{ selectedRowKeys: selectedBudgetItemRowKeys, onChange: onSelectBudgetItemChange }"
              >
                <a-table
                  class="inner-table"
                  :scroll="{ x: true }"
                  slot="expandedRowRender"
                  slot-scope="group"
                  :columns="budgetListColumns"
                  :data-source="group.budgetList"
                  rowKey="projectBudgetCode"
                  :pagination="false"
                >
                  <template slot="changeAmount" slot-scope="text, record">
                    <a-input
                      placeholder="请输入数字"
                      v-model="record.changeAmount"
                      @blur="(event) => changeAmountChange(event, record)"
                      :disabled="projectChangeData.status && projectChangeData.status != '1'"
                    />
                  </template>
                  <template slot="originAmount" slot-scope="text">
                    <span>{{ parseFloat(text).toLocaleString() }}</span>
                  </template>
                  <template slot="historyChangeAmount" slot-scope="text">
                    <span>{{ parseFloat(text).toLocaleString() }}</span>
                  </template>
                  <template slot="memo" slot-scope="text, record">
                    <a-textarea
                      placeholder="请输入说明内容"
                      auto-size
                      v-model="record.memo"
                      :disabled="projectChangeData.status && projectChangeData.status != '1'"
                    />
                  </template>
                </a-table>
                <template slot="factoryName" slot-scope="text, record">
                  <a-select
                    style="width: 100%"
                    v-model="record.factoryCode"
                    :options="factoryOptions"
                    @change="(value) => selectFactoryChange(value, record)"
                    :disabled="projectChangeData.status && projectChangeData.status != '1'"
                  >
                  </a-select>
                </template>
                <template slot="factory" slot-scope="text, record">
                  <span>{{ record.factoryCode + '(' + record.factory + ')' }}</span>
                </template>
                <template slot="costCenterNo" slot-scope="text, record">
                  <a-textarea
                    placeholder="请输入成本中心号"
                    auto-size
                    v-model="record.costCenterNo"
                    :disabled="projectChangeData.status && projectChangeData.status != '1'"
                  />
                </template>
              </a-table>-->
              <ExpandedRowsTable
                style="margin-top: 5px; margin-bottom: 5px"
                ref="expandTreeTable"
                :data="budgetItemTree"
                :loading="tabLoading"
                :columns="changeCols"
                :rowKey="rowKey"
                :editTable="btnShow"
                :rowSelection="rowSelection"
                @changeAmountChange="changeAmountChange"
              >
              </ExpandedRowsTable>
              <ul class="totalExpenses">
                <li>
                  原来预算总费用（元）：
                  <span>￥</span><span>{{ totalAmount }}</span
                  ><span>（￥</span>{{ totalTenThousand }}<span style="margin-right: 20px">万）</span>
                  <span style="color: red">
                    本次变更总费用（元）：
                    <span>￥</span><span>{{ totalAmountChange }}</span
                    ><span>（￥</span>{{ totalTenThousandChange }}<span style="margin-right: 20px">万）</span>
                  </span>
                  历史变更总费用（元）：
                  <span>￥</span><span>{{ amountHistory }}</span
                  ><span>（￥</span>{{ amountHistoryTenThousand }}<span>万）</span>
                  <span style="color: red">
                    变更费用百分比：
                    <span>{{ changePercent + '%' }}</span>
                  </span>
                </li>
              </ul>
            </a-row>
            <a-row
              v-show="
                projectBuildData.projectClass === '40' &&
                projectChangeData.status > 1 &&
                projectChangeData.changeType === '土建'
              "
            >
              <a-icon type="transaction" style="margin-right: 5px" id="costAuditRemark" /><span
                style="font-weight: bolder"
                >造价员审核结论</span
              >
              <a-form-model-item prop="costAuditRemark">
                <a-textarea
                  v-model="projectChangeData.costAuditRemark"
                  placeholder="请输入审核结论"
                  auto-size
                  style="margin-top: 5px; border-color: red"
                  :readOnly="currentNodeDefKey !== 'costDepartment' && currentNodeDefKey !== 'costDepartmentSupervisor'"
                />
              </a-form-model-item>
            </a-row>
            <a-row v-if="projectChangeData.status === 3">
              <a-col :span="24">
                <a-icon type="money-collect" style="margin-right: 5px" /><span style="font-weight: bolder"
                  >预算下达情况</span
                >
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="下达状态"
                  prop="budgetStatus"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 21 }"
                >
                  <span
                    :style="{
                      color:
                        projectChangeData.budgetStatus === 2
                          ? 'green'
                          : projectChangeData.budgetStatus === 1
                          ? 'orange'
                          : 'red',
                    }"
                  >
                    {{
                      projectChangeData.budgetStatus === 2
                        ? '已下达'
                        : projectChangeData.budgetStatus === 1
                        ? '已调整WBS'
                        : '未下达'
                    }}
                  </span>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="调整WBS备注"
                  prop="wbsMemo"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 21 }"
                >
                  <a-textarea
                    v-model="projectChangeData.wbsMemo"
                    auto-size
                    style="margin-top: 5px"
                    readOnly
                    :disabled="projectChangeData.status && projectChangeData.status != '1'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="下达预算备注"
                  prop="giveBudgetMemo"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 21 }"
                >
                  <a-textarea
                    v-model="projectChangeData.giveBudgetMemo"
                    auto-size
                    style="margin-top: 5px"
                    readOnly
                    :disabled="projectChangeData.status != '1'"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-icon type="menu-unfold" style="margin-right: 5px" /><span style="font-weight: bolder"
                >其他变更内容</span
              >
              <a-form-model-item prop="changeContent">
                <a-checkbox-group
                  v-model="changeContentList"
                  :options="changeContentOptions"
                  @change="changeContentChange"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                />
              </a-form-model-item>
            </a-row>
            <a-row>
              <a-icon type="question-circle" style="margin-right: 5px" /><span style="font-weight: bolder"
                >变更原因说明</span
              >
              <a-form-model-item prop="changeReason">
                <a-textarea
                  v-model="projectChangeData.changeReason"
                  placeholder="请输入变更原因"
                  auto-size
                  style="margin-top: 5px; border-color: red"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                />
              </a-form-model-item>
            </a-row>
            <a-row>
              <a-icon type="edit" style="margin-right: 5px" /><span style="font-weight: bolder"
                >变更后对项目的影响分析</span
              >
              <a-form-model-item prop="changeInfluence">
                <a-textarea
                  v-model="projectChangeData.changeInfluence"
                  placeholder="请输入变更后对项目的影响"
                  auto-size
                  style="margin-top: 5px; border-color: red"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                />
              </a-form-model-item>
            </a-row>
          </a-form-model>
          <div class="influence-module">
            <h4>影响模块</h4>
            <div class="btn-box">
              <a-button type="primary" style="width: 80px; margin-right: 15px" @click="addInfluence" v-if="btnShow"
                >新增</a-button
              >
              <a-button style="width: 80px; margin-right: 15px" @click="delInfluenceData" v-if="btnShow">删除</a-button>
              <span class="infoTips">
                <a-icon type="exclamation-circle" theme="filled" style="color: #47a4fa" />
                变更项目涉及的影响部门、人员请填写在此处，系统自动归入审批流程的【相关主管会审】步骤，在流程中一起会审。
              </span>
            </div>
            <a-table
              :columns="influenceList"
              :data-source="influenceData"
              bordered
              rowKey="rowIndex"
              :pagination="false"
              style="margin-top: 5px"
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            >
              <template slot="deptName" slot-scope="text, record">
                <a-input
                  placeholder="输入部门全称"
                  v-model="record.deptName"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                />
              </template>
              <template slot="userName" slot-scope="text, record">
                <span style="line-height: 30px">{{ record.userName }}</span>
                <a-button
                  style="border: none; background-color: unset; margin: unset; width: auto; float: right"
                  size="small"
                  @click="selectUser(record)"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                  >➕</a-button
                >
              </template>
              <template slot="sendingFlag" slot-scope="text, record">
                <a-select
                  style="width: 100%"
                  v-model="record.isSendTask"
                  :disabled="projectChangeData.status && projectChangeData.status != '1'"
                >
                  <a-select-option value="true"> 是 </a-select-option>
                  <a-select-option value="false"> 否 </a-select-option>
                </a-select>
              </template>
            </a-table>
          </div>
          <div class="influence-module">
            <h4>附件列表</h4>
            <span class="infoTips" style="margin-left: 15px" v-show="!projectChangeData.id">
              <a-icon type="exclamation-circle" theme="filled" style="color: #47a4fa" />
              需要先保存变更单后，才能对变更单上传附件。
            </span>
            <div class="btn-box" v-show="downloadAndView">
              <ht-upload
                v-if="projectChangeData.id > 0"
                ref="myUpload"
                class="upload-demo"
                multiple
                dbKey="Trd"
                :busField="projectChangeData.id.toString()"
                busType="projectChange"
                :busKey="projectBuildId"
                ftpKey="ftp"
                v-model="attachmentData"
                :show-file-list="false"
              >
                <el-button
                  v-if="projectChangeData.id > 0 && (['1','2'].indexOf(projectChangeData.status)>-1 || attachEdit)"
                  size="small"
                  type="primary"
                  >新增附件</el-button
                >
              </ht-upload>
              <a-button
                type="primary"
                style="width: 80px; margin-left: 15px"
                v-show="downloadAndView"
                @click="downLoadBatch"
                >下载</a-button
              >
              <a-button
                style="width: 80px; margin-left: 15px"
                v-show="attachEdit || ['1','2'].indexOf(projectChangeData.status)>-1"
                @click="deleteBatch"
                >删除</a-button
              >
            </div>
            <a-table
              :columns="fileList"
              :data-source="attachmentDataList"
              bordered
              :pagination="false"
              style="margin-top: 5px"
              rowKey="key"
              :row-selection="{ selectedRowKeys: selectedAttachRowKeys, onChange: onSelectAttachChange }"
            >
              <template slot="fileName" slot-scope="text, record">
                <a @click="showAttach(record.key, record.uploader, record.fileName, true)">{{ record.fileName }}</a>
              </template>
            </a-table>
          </div>
          <div class="influence-module" v-if="valueTestChangeLog.length > 0">
            <h4>价值表核心力变更内容</h4>
            <br />
            <a-icon type="snippets" style="margin-right: 5px" />原项目等级绩点：
            <div class="info-detail">
              <ul class="info-list">
                <li>
                  <span class="list-title">项目等级：</span>
                  <span class="redfont">
                    {{ originLevelData.projectLevel ? originLevelData.projectLevel : '--' }}
                  </span>
                </li>
                <li>
                  <span class="list-title">X创新绩点：</span>
                  <span class="redfont borderleft">
                    {{
                      originLevelData.gradePoint && originLevelData.gradePoint > 0 ? originLevelData.gradePoint : '--'
                    }}分
                  </span>
                </li>
                <li>
                  <span class="list-title">Y基本绩点：</span>
                  <span class="redfont borderleft">
                    {{
                      originLevelData.gradePointBasic && originLevelData.gradePointBasic > 0
                        ? originLevelData.gradePointBasic
                        : '--'
                    }}分
                  </span>
                </li>
                <li>
                  <span class="list-title">核心力值：</span>
                  <span class="redfont borderleft">
                    {{
                      originLevelData.gradePointCore && originLevelData.gradePointCore > 0
                        ? originLevelData.gradePointCore
                        : '--'
                    }}分
                  </span>
                </li>
              </ul>
            </div>
            <a-icon type="snippets" style="margin-right: 5px" />变更后项目等级绩点：
            <div class="info-detail">
              <ul class="info-list">
                <li>
                  <span class="list-title">项目等级：</span>
                  <span class="redfont">
                    {{ changeLevelData.projectLevel ? changeLevelData.projectLevel : '--' }}
                  </span>
                </li>
                <li>
                  <span class="list-title">X创新绩点：</span>
                  <span class="redfont borderleft">
                    {{
                      changeLevelData.gradePoint && changeLevelData.gradePoint > 0 ? changeLevelData.gradePoint : '--'
                    }}分
                  </span>
                </li>
                <li>
                  <span class="list-title">Y基本绩点：</span>
                  <span class="redfont borderleft">
                    {{
                      changeLevelData.gradePointBasic && changeLevelData.gradePointBasic > 0
                        ? changeLevelData.gradePointBasic
                        : '--'
                    }}分
                  </span>
                </li>
                <li>
                  <span class="list-title">核心力值：</span>
                  <span class="redfont borderleft">
                    {{
                      changeLevelData.gradePointCore && changeLevelData.gradePointCore > 0
                        ? changeLevelData.gradePointCore
                        : '--'
                    }}分
                  </span>
                </li>
              </ul>
            </div>
          </div>
          <div class="change-record" v-if="changeLogShow">
            <h4>变更日志</h4>
            <span class="infoTips" style="margin-left: 15px">
              <a-icon type="exclamation-circle" theme="filled" style="color: #47a4fa" />
              点击可展开查看相应变更日志
            </span>
            <ul class="record-container">
              <li v-if="baseInfoChangeLog.length > 0">
                <a-collapse v-model="activeKey">
                  <a-collapse-panel key="1" header="基本信息">
                    <a-timeline>
                      <a-timeline-item v-for="log in baseInfoChangeLog" v-bind:key="log.id">
                        <div>
                          {{ log.userName + ' ' + log.logContent }}
                        </div>
                        <div>{{ log.logTime }}</div>
                      </a-timeline-item>
                    </a-timeline>
                  </a-collapse-panel>
                </a-collapse>
              </li>
              <li v-if="valueTestChangeLog.length > 0">
                <a-collapse>
                  <a-collapse-panel key="1" header="价值表核心力值">
                    <a-timeline>
                      <a-timeline-item v-for="log in valueTestChangeLog" v-bind:key="log.id">
                        <div>
                          {{ log.userName + ' ' + log.logContent }}
                        </div>
                        <div>{{ log.logTime }}</div>
                      </a-timeline-item>
                    </a-timeline>
                  </a-collapse-panel>
                </a-collapse>
              </li>
              <li v-if="timeChangeLog.length > 0">
                <a-collapse>
                  <a-collapse-panel key="1" header="时间表">
                    <a-timeline>
                      <a-timeline-item v-for="log in timeChangeLog" v-bind:key="log.id">
                        <div>
                          {{ log.userName + ' ' + log.logContent }}
                        </div>
                        <div>{{ log.logTime }}</div>
                      </a-timeline-item>
                    </a-timeline>
                  </a-collapse-panel>
                </a-collapse>
              </li>
              <li v-if="teamChangeLog.length > 0">
                <a-collapse>
                  <a-collapse-panel header="团队表">
                    <a-timeline>
                      <a-timeline-item v-for="log in teamChangeLog" v-bind:key="log.id">
                        <div>
                          {{ log.userName + ' ' + log.logContent }}
                        </div>
                        <div>{{ log.logTime }}</div>
                      </a-timeline-item>
                    </a-timeline>
                  </a-collapse-panel>
                </a-collapse>
              </li>
              <li v-if="attachChangeLog.length > 0">
                <a-collapse>
                  <a-collapse-panel header="上传附件">
                    <a-timeline>
                      <a-timeline-item v-for="log in attachChangeLog" v-bind:key="log.id">
                        <div>
                          {{ log.userName + ' ' + log.logContent }}
                        </div>
                        <div>{{ log.logTime }}</div>
                      </a-timeline-item>
                    </a-timeline>
                  </a-collapse-panel>
                </a-collapse>
              </li>
            </ul>
          </div>
          <div class="influence-module" v-if="processInstanceId && processInstanceId !== ''">
            <h4>审批意见</h4>
            <div class="process-engine" style="width: 100%">
              <ht-approval
                ref="childrenRef"
                :process-instance-id="processInstanceId"
                :options="options"
                :custom="custom"
                :before-submit="beforeSubmit"
                :before-reject="beforeReject"
                :show-task-history="true"
                :history-dialog="historyDialog"
                :task-load="taskLoad"
                :message-id="messageId"
                :show-upload-btn="false"
                :hidden-task-def-key="hiddenTaskDefKey"
                :print="print"
                :snapshotConfigs="snapshotConfigs"
              >
              </ht-approval>
            </div>
          </div>
          <div class="btn">
            <a-button size="large" @click="save" :loading="btnLoading" v-if="btnShow">保存</a-button>
            <a-button
              size="large"
              type="primary"
              @click="onSubmit1"
              :loading="btnLoading"
              v-if="btnShow && projectChangeData.id"
              >提交审批
            </a-button>
            <a-button
              size="large"
              @click="del"
              :loading="btnLoading"
              style="color: red"
              v-if="
                projectChangeData.status &&
                projectChangeData.status === 1 &&
                (projectChangeData.createUserId === currentUserId ||projectBuildData.projectSubTypeAdmin)
              "
              >删除</a-button
            >
          </div>
          <user-select ref="userSelect" :limit="limit" @setResult="setResult" :origin-target-keys="originTargetKeys" />
          <process-user-select :columns="selUserCols" @selectUserConfirm="selectUserConfirm" ref="processUserSelect" />
          <ProcessUserSelect1 @selectUserConfirm1="selectUserConfirm1" ref="processUserSelect1" />

          <!--选择费用支出公司模态框-->
          <a-modal title="选择费用支出公司" :visible="showAddFactory" @ok="doAddFactory" @cancel="cancelAddFactory">
            <ul class="info-list">
              <li style="margin-bottom: 20px">
                <img src="@/assets/dbcircle.png" alt="" />
                <span class="list-title">选择费用支出公司：</span>
                <a-input-search
                  placeholder="费用支出公司"
                  readOnly
                  v-model:value="selectFactoryData.name"
                  @click="openFactorySelector()"
                  style="width: 250px"
                />
              </li>
              <li style="margin-bottom: 20px">
                <img src="@/assets/dbcircle.png" alt="" />
                <span class="list-title">选择成本中心号：</span>
                <a-input style="width: 250px" placeholder="请选择成本中心号" v-model="addCostCenterNo" readOnly @click="selectCostCenter"/>
              </li>
            </ul>
          </a-modal>
          <a-modal title="修改成本中心号" :visible="showChangeCenter" @ok="doChangeCenter" @cancel="showChangeCenter=false">
            <ul class="info-list">
              <li style="margin-bottom: 20px">
                <img src="@/assets/dbcircle.png" alt="" />
                <span class="list-title">原成本中心号：</span>
                <span>{{selectedBudgetItemRows.length?(selectedBudgetItemRows[0].originCostCenterNo?selectedBudgetItemRows[0].originCostCenterNo:selectedBudgetItemRows[0].costCenterNo):''}}</span>
              </li>
              <li style="margin-bottom: 20px">
                <img src="@/assets/dbcircle.png" alt="" />
                <span class="list-title">选择成本中心号：</span>
                <a-input style="width: 250px" placeholder="请选择成本中心号" v-model="addCostCenterNo" readOnly @click="selectCostCenter"/>
              </li>
            </ul>
          </a-modal>
          <a-modal
            title="项目变更历史记录"
            :visible="showHistoryList"
            @ok="showHistoryList = false"
            @cancel="showHistoryList = false"
            width="80vw"
            :height="800"
            :destroyOnClose="true"
          >
            <change-history-list :projectBuildId="projectBuildId"></change-history-list>
          </a-modal>

          <a-modal
            title="项目信息打印"
            :visible="printModalShowFlag"
            @ok="printModalShowFlag = false"
            @cancel="printModalShowFlag = false"
            width="100%"
            wrap-class-name="full-modal"
            :destroyOnClose="true"
            :footer="null"
            :key="printKey"
          >
            <project-build-change-print :projectBuildData="projectBuildData" :projectChangeData="projectChangeData" :change-id="changeId" :freshKey="printKey"></project-build-change-print>
          </a-modal>
          <!--成本中心号选择-->
          <table-select-modal
            ref="costCenterSelect"
            :title="costCenterData.title"
            :searchPlaceholder="costCenterData.searchPlaceholder"
            :importColumns="costCenterData.columns"
            :params="costCenterData.params"
            :keywordKey="costCenterData.keywordKey"
            :isAllSelect="false"
            :listUrl="costCenterData.url"
            @ok="costCenterHandleOk"
          />
          <FactorySelector @close="selectFactorySelector" ref="FactorySelector" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { USER_NAME, ACCESS_TOKEN } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
import { httpAction, getAction, postAction, postActionAsync, getActionAsync ,previewAttach} from '@/api/manage'
import { getParamValFromUrl, formatFileSize, endWith } from '@/utils/common.js'
import '@/config/upload.install.js'

export default {
  components: {
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    UserSelect: () => import('@/components/tools/UserSelect'),
    ProcessUserSelect: () => import('@/components/tools/projectBuildStup/ProcessUserSelect'),
    ProcessUserSelect1: () => import('@/components/tools/projectBuildStup/ProcessUserSelect1'),
    ChangeHistoryList: () => import('@/components/tools/projectBuild/ChangeHistoryList'),
    ProjectBuildChangePrint: () => import('@/views/projectBuild/projectPrint/ProjectBuildChangePrint'),
    ExpandedRowsTable: () => import('@/views/projectBuild/budgetManage/orderInfo/expandedRowsTable'),
    TableSelectModal:()=>import('@/components/tools/TableSelectModal'),
    FactorySelector: () => import('@/views/projectChange/FactorySelector'),
  },
  data() {
    return {
      budgetChangeContentOptions: [
        { label: '项目总预算调整', value: '1', disabled: false },
        { label: '项目内预算调整', value: '2', disabled: false },
        { label: '费用支出公司变更', value: '3', disabled: false },
      ],
      budgetChangeContentList: [],
      changeContentOptions: [
        { label: '基本信息', value: '0', disabled: false },
        { label: '价值表', value: '2', disabled: false },
        { label: '核心力值表', value: '3', disabled: false },
        { label: '时间表', value: '1', disabled: false },
        // { label: '预算表', value: '4' ,disabled: false},
        { label: '团队表', value: '5', disabled: false },
        // { label: '附件表', value: '6' ,disabled: false},
      ],
      changeContentList: [],
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'changeRecord',
      },
      submitBtnShow: false,
      btnShow: false,
      reserveBtnShow: false,
      changeLogShow: false,
      btnLoading: false,
      showHistoryList: false,
      projectBuildId: this.$route.query.projectBuildId,
      changeId: this.$route.query.changeId,
      processInstanceId: '',
      options: {
        request: {
          baseUrl: this.API_BASE_URL, // 业务系统根路径
          timeOut: 5000, // 请求超时时间
          interceptors: (config) => {
            config.headers['X-Access-Token'] = Vue.ls.get(ACCESS_TOKEN)
            return config
          },
        },
        userId: Vue.ls.get(USER_NAME),
      },
      currentNodeDefKey: '',
      custom: {},
      historyDialog: {
        // 审批历史模态框属性
      },
      messageId: '', // 工作台URL里面的msgId参数
      showPrintBtn: false,
      hiddenTaskDefKey: 'submit',
      currentUserId: Vue.ls.get(USER_NAME),
      url: {
        checkChangeCycleRules: '/projectBuildTime/checkProjectChangeCycleRules',
        queryBuildById: '/projectBuild/getNormalVo',
        getProjectBuildTabShowStatus: '/projectBuild/getProjectBuildTabShowStatus',
        queryOriginListByBuildId: '/projectBuildBudget/queryVoListByBuildId',
        queryChangeByBuildId: '/projectChange/queryByBuildId',
        queryChangeById: '/projectChange/queryById',
        queryChangeBudgetItemById: '/projectChange/queryChangeBudgetItemTree',
        queryChangeInfluenceData: '/projectChange/queryChangeInfluenceData',
        queryChangeLog: '/projectChange/queryChangeLog',
        queryChangeLevelInfo: '/projectChange/queryChangeLevelInfo',
        getCodeInfoList: '/manage/codeInfo/queryByType',
        saveChange: '/projectChange/save',
        delChange: '/projectChange/delete',
        submitChange: '/projectChange/submit',
        saveCostAuditRemark: '/projectChange/saveCostAuditRemark',
        auditPass: '/projectChange/auditPass',
        auditNotPass: '/projectChange/auditNotPass',
        auditBack: '/projectChange/auditBack',
        auditCancel: '/projectChange/auditCancel',
        calcChangeRecordFlow: '/projectChange/calcChangeRecordFlow',
        startProcessFlow: '/projectChange/startProcessFlow',
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: '',
      projectBuildData: {},
      projectChangeData: {
        id: 0,
        projectChangeNo: '',
        dutyDeptName: '',
        dutyUserName: '',
        changeReason: '',
        changeType: '',
        changeInfluence: '',
        changeTotal: '',
        addToSapTotal: '',
        changeContent:'',
      },
      originLevelData: {},
      changeLevelData: {},
      rules: {
        dutyDeptName: [{ required: true, message: '请输入主要责任部门', trigger: 'blur' }],
        dutyUserName: [{ required: true, message: '请选择主要负责人', trigger: 'change' }],
        changeReason: [{ required: true, message: '请输入变更原因', trigger: 'blur' }],
        changeType: [{ required: true, message: '请选择变更类型', trigger: 'blur' }],
        changeInfluence: [{ required: true, message: '请输入变更后对项目的影响', trigger: 'blur' }],
        changeTotal: [{ required: true, message: '请输入变更费用', trigger: 'blur' }],
        addToSapTotal: [{ required: true, message: '请输入追加至SAP系统费用', trigger: 'blur' }],
      },
      influenceList: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 80,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '部门',
          width: '50%',
          align: 'center',
          dataIndex: 'deptName',
          key: 'deptName',
          scopedSlots: { customRender: 'deptName' },
        },
        {
          title: '人员',
          align: 'center',
          dataIndex: 'userName',
          key: 'userName',
          scopedSlots: { customRender: 'userName' },
        },
      ],
      originTargetKeys: [],
      budgetGroupColumns: [
        {
          title: '费用支出公司',
          width: '485px',
          align: 'center',
          dataIndex: 'factoryName',
          key: 'factoryName',
          scopedSlots: { customRender: 'factoryName' },
        },
        {
          title: '代码',
          width: '150px',
          align: 'center',
          dataIndex: 'factory',
          key: 'factory',
          scopedSlots: { customRender: 'factory' },
        },
        {
          title: '成本中心号',
          width: '485px',
          align: 'center',
          dataIndex: 'costCenterNo',
          key: 'costCenterNo',
          scopedSlots: { customRender: 'costCenterNo' },
        },
      ],
      budgetListColumns: [
        { title: '分项名称', width: '150px', align: 'center', dataIndex: 'budgetItem', key: 'budgetItem' },
        { title: 'WBS号', width: '120px', align: 'center', dataIndex: 'wbsConcat', key: 'wbsConcat' },
        {
          title: '原预算金额',
          width: '120px',
          align: 'center',
          dataIndex: 'originAmount',
          key: 'originAmount',
          scopedSlots: { customRender: 'originAmount' },
        },
        {
          title: '本次变更费用',
          width: '150px',
          align: 'right',
          dataIndex: 'changeAmount',
          key: 'changeAmount',
          scopedSlots: { customRender: 'changeAmount' },
        },
        {
          title: '历史变更汇总',
          width: '150px',
          align: 'right',
          dataIndex: 'historyChangeAmount',
          key: 'historyChangeAmount',
          scopedSlots: { customRender: 'historyChangeAmount' },
        },
        {
          title: '变更说明',
          width: '479px',
          align: 'center',
          dataIndex: 'memo',
          key: 'memo',
          scopedSlots: { customRender: 'memo' },
        },
      ],
      changeCols: [
        {title: '层级',dataIndex: 'wbsLevel',key: 'wbsLevel',align: 'center',width: '120px'},
        {title: 'WBS号',dataIndex: 'wbsConcat',key: 'wbsConcat',width: '150px',},
        {title: 'WBS名称',dataIndex: 'wbsName',key: 'wbsName',width: 200,scopedSlots: { customRender: 'wbsName' }},
        {title: '不含税金额(元)',dataIndex: 'originAmount',key: 'originAmount',width: 120,align: 'right',scopedSlots: { customRender: 'originAmount' }},
        {title: '费用类型',dataIndex: 'budgetItem', key: 'budgetItem',width: 120,align: 'center',},
        {title: '本次调整预算(元)',dataIndex: 'changeAmount',key: 'changeAmount',width: 130,align: 'right',scopedSlots: { customRender: 'changeAmount' }},
        {title: '预算变更说明',dataIndex: 'memo',key: 'memo',width: 200,align: 'center',scopedSlots: { customRender: 'changeMemo' }},
        {title: '历史变更总额',dataIndex: 'historyChangeAmount', key: 'historyChangeAmount',width: 100,align: 'right',scopedSlots: { customRender: 'historyChangeAmount' }},
        {title: '公司代码(编码)',dataIndex: 'factoryCode',key: 'factoryCode',width:120,align: 'center',scopedSlots: { customRender: 'factoryCode' }},
        {title: '成本中心号',dataIndex: 'costCenterNo',key: 'costCenterNo',width: 100,align: 'center',},
        {title: '原成本中心号',dataIndex: 'originCostCenterNo',key: 'originCostCenterNo',width: 100,align: 'center',},
        {title: '状态',dataIndex: 'status',key: 'status',width: 60,align: 'center',scopedSlots: { customRender: 'changeStatus' }},
      ],
      rowKey:'wbsConcat',
      tabLoading:false,
      budgetItemTree:[],
      fileList: [
        {
          title: '附件名称',
          width: '25%',
          align: 'center',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'fileName' },
        },
        { title: '附件大小', width: '25%', align: 'center', dataIndex: 'size', key: 'size' },
        { title: '上传时间', width: '25%', align: 'center', dataIndex: 'uploadTime', key: 'uploadTime' },
        { title: '上传者', width: '25%', align: 'center', dataIndex: 'uploaderName', key: 'uploaderName' },
      ],
      attachmentData: [],
      attachmentDataList: [],
      selectedAttachRowKeys: [],
      selectedAttachRows:[],
      attach: {
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/common/deleteBatch',
      },
      downloadAndView: false,
      attachEdit: false,
      changeTypeData: [],
      changeTypeOptions: [],
      influenceData: [],
      baseInfoChangeLog: [],
      valueTestChangeLog: [],
      timeChangeLog: [],
      teamChangeLog: [],
      attachChangeLog: [],
      selectedRowKeys: [],
      selectedRow: [],
      selectedBudgetItemRowKeys: [],
      selectedBudgetItemRows: [],
      selectUserType: '',
      limit: 1,
      currentRecord: null,
      selUserCols: [],
      engineeringUserCols: [
        { label: '专业负责人', field: 'disciplineLeaderUser', username: '', realname: '', required: true },
        {
          label: '相关专业负责人及部门主管',
          field: 'disciplineLeaderSupervisorUser',
          username: '',
          realname: '',
          required: true,
        },
        { label: '造价部门专员', field: 'costDepartmentUser', username: '', realname: '', required: false },
        { label: '造价部门主管', field: 'costDepartmentSupervisorUser', username: '', realname: '', required: false },
        { label: '项目经理A', field: 'projectManagerUser', username: '', realname: '', required: true },
      ],
      civilEngineeringUserCols: [
        { label: '专业负责人', field: 'disciplineLeaderUser', username: '', realname: '', required: true },
        {
          label: '相关专业负责人及部门主管',
          field: 'disciplineLeaderSupervisorUser',
          username: '',
          realname: '',
          required: true,
        },
        { label: '造价部门专员', field: 'costDepartmentUser', username: '', realname: '', required: true },
        { label: '造价部门主管', field: 'costDepartmentSupervisorUser', username: '', realname: '', required: true },
        { label: '项目经理A', field: 'projectManagerUser', username: '', realname: '', required: true },
      ],
      otherUserCols: [
        { label: '部门主管', field: 'departmentManagerUser', username: '', realname: '', required: true },
      ],
      company64UserCols: [
        { label: '经营体负责人', field: 'businessManagerUser', username: '', realname: '', required: true },
          {
            label: '会审',
            field: 'jointHearingUser',
            username: 'guanjh,liaoch,lij5',
            realname: '管江华,廖长辉,李军A',
            required: true,
          },
          { label: '董秘办审批', field: 'secretaryOfficeUser', username: 'zhangx', realname: '张欣', required: true },
          { label: '集团审批', field: 'groupAuditUser', username: 'zhangr', realname: '张蓉', required: true },
      ],
      changeBudgetItemData: [],
      budgetGroups: [],
      selectBudgetItem: {
        visible: false,
        selectedRowKeys: [],
        selectedRows: [],
      },
      showAddFactory: false,
      showChangeCenter: false,
      factoryOptions: [],
      factoryData: [],
      selectFactoryData: {},
      addCostCenterNo:'',
      budgetItemData: [],
      totalAmount: '',
      totalTenThousand: '',
      totalAmountChange: '',
      totalTenThousandChange: '',
      amountHistory: '',
      amountHistoryTenThousand: '',
       snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper'
        }
      ],
      activeKey: ['1'],
      printModalShowFlag: false,
      printKey: 1,
      selectBudgetChangeContent:false,
      costCenterData:{
        title:'选择成本中心号',
        searchPlaceholder:'请输入关键词进行模糊搜索',
        visible:false,
        url:'/costCenter/list',
        params:{companyCode:'',costCenterName:''},
        keywordKey:"costCenterName",
        columns: [
          {
            title: '成本中心号',
            dataIndex: 'costCenter',
            align: 'center',
          },
          {
            title: '成本中心名称',
            dataIndex: 'costCenterName',
            align: 'center',
          },
        ],
      },
    }
  },
  computed: {
    changePercent() {
      let amountHistory = this.amountHistory
      let totalAmountChange = this.totalAmountChange
      let totalAmount = this.totalAmount
      if (amountHistory) {
        amountHistory = amountHistory.replace(new RegExp(',', 'gm'), '')
      } else {
        amountHistory = 0
      }
      if (totalAmountChange) {
        totalAmountChange = totalAmountChange.replace(new RegExp(',', 'gm'), '')
      } else {
        amountHistory = 0
      }
      if (totalAmount) {
        totalAmount = totalAmount.replace(new RegExp(',', 'gm'), '')
      } else {
        return null
      }
      return (((parseFloat(amountHistory) + parseFloat(totalAmountChange)) / parseFloat(totalAmount)) * 100).toFixed(3)
    },
    isUpper() {
      if (this.changePercent > 20) {
        return '1'
      }
      return '0'
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedBudgetItemRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.onSelectBudgetItemChange(selectedRowKeys, selectedRows)
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.wbsLevel <2,
            name: record.name,
          },
        }),
      };
    },
  },
  mounted() {
    this.getProjectBuildData()
    this.getChangeTypeData()
  },
  watch: {
    attachmentData: function (newQuestion, oldQuestion) {
      // this.bindBusKey();
      this.attachDataListFresh()
    },
  },
  methods: {
    getProjectBuildData: function () {
      getAction(this.url.queryBuildById, { id: this.projectBuildId }).then((res) => {
        this.projectBuildData = res.result || {}
        this.reserveBtnShow =
          (this.projectBuildData.projectManagers.indexOf(this.currentUserId) >= 0 ||
            this.projectBuildData.assistantProjectManagers.indexOf(this.currentUserId) >= 0 ||
            this.projectBuildData.projectSubTypeAdmin) &&
          res.result.status >= 4 &&
          res.result.status !== 6 &&
          res.result.status !== 7
        this.getProjectChangeData()
        this.getProjectBuildTabShowStatus()
        this.getFactoryData()
        this.getBudgetItemData()
      })
    },
    getProjectBuildTabShowStatus() {
      const that = this
      getAction(this.url.getProjectBuildTabShowStatus, { id: this.projectBuildId })
        .then((res) => {
          if (res.success) {
            if (
              !res.result.showQuest ||
              (that.projectBuildData.projectClass == '40' &&
                that.projectBuildData.projectMembers.indexOf(that.currentUserId) >= 0)
            ) {
              that.changeContentOptions.forEach(function (item, index) {
                if (that.projectBuildData.status !== 4 && that.projectBuildData.status !== 5) {
                  item.disabled = true
                }
                if (item.value === '2') {
                  that.changeContentOptions.splice(index, 1)
                }
              })
            }
            if (
              !res.result.showCoreQuest ||
              (that.projectBuildData.projectClass == '40' &&
                that.projectBuildData.projectMembers.indexOf(that.currentUserId) >= 0)
            ) {
              that.changeContentOptions.forEach(function (item, index) {
                if (item.value === '3') {
                  that.changeContentOptions.splice(index, 1)
                }
              })
            }
            // if (
            //   that.projectBuildData.projectClass == '40' &&
            //   that.projectBuildData.projectMembers.indexOf(that.currentUserId) >= 0
            // ) {
            //   that.changeContentOptions.splice(that.changeContentOptions.length - 1, 1)
            // }
          } else {
            that.$message.warning('判断价值表/上会是否显示失败:' + res.message)
          }
        })
        .catch((res) => {
          that.$message.warning('判断价值表/上会是否显示异常:' + res.message)
        })
    },
    getChangeTypeData() {
      const that = this
      getAction(this.url.getCodeInfoList, { type: '项目变更类型' }).then((res) => {
        this.changeTypeData = res.result || []
        if (this.changeTypeData.length > 0) {
          this.changeTypeData.forEach(function (item) {
            that.changeTypeOptions.push({ value: item.name.trim(), label: item.name.trim() })
          })
        }
      })
    },
    getFactoryData() {
      const that = this
      getAction(this.url.getCodeInfoList, { type: '项目需求公司' }).then((res) => {
        this.factoryData = res.result || []
        if (this.factoryData.length > 0) {
          this.factoryData.forEach(function (item) {
            that.factoryOptions.push({ value: item.parentid.trim(), label: item.name })
          })
        }
      })
    },
    getBudgetItemData() {
      const that = this
      getAction(this.url.getCodeInfoList, { type: this.projectBuildData.projectType + '类项目预算项' }).then((res) => {
        that.budgetItemData = res.result || []
      })
    },
    getProjectChangeData() {
      let url = '',
        param = {}
      if (this.changeId) {
        url = this.url.queryChangeById
        param = { id: this.changeId }
      } else {
        url = this.url.queryChangeByBuildId
        param = { buildId: this.projectBuildId }
      }
      getAction(url, param).then((res) => {
        if (res.result) {
          this.projectChangeData = res.result
          if (
            (this.projectBuildData.status === 4 || this.projectBuildData.status === 5||(this.projectBuildData.status===6&&this.projectBuildData.projectClass=='30')) &&
            (this.projectBuildData.projectManagers.indexOf(this.currentUserId) >= 0 ||
              this.projectBuildData.assistantProjectManagers.indexOf(this.currentUserId) >= 0 ||
              this.projectBuildData.projectMembers.indexOf(this.currentUserId) >= 0 ||
              this.projectBuildData.submitUserId == this.currentUserId ||
              this.projectBuildData.projectSubTypeAdmin) &&
            res.result.status === 1
          ) {
            this.btnShow = true
          } else {
            this.btnShow = false
          }
          if (
            this.projectBuildData.projectManagers.indexOf(this.currentUserId) >= 0 ||
            this.projectBuildData.assistantProjectManagers.indexOf(this.currentUserId) >= 0 ||
            (this.projectChangeData.auditUserIds != null &&
              this.projectChangeData.auditUserIds.indexOf(this.currentUserId) >= 0) ||
            (this.projectChangeData.copyForUserIds != null &&
              this.projectChangeData.copyForUserIds.indexOf(this.currentUserId) >= 0) ||
            this.projectBuildData.projectMembers.indexOf(this.currentUserId) >= 0 ||
            this.projectBuildData.submitUserId == this.currentUserId ||
            this.projectBuildData.projectSubTypeAdmin
          ) {
            this.attachEdit = true
          } else {
            this.attachEdit = false
          }
          this.downloadAndView = !!(
            this.attachEdit ||
            this.projectBuildData.downAndView ||
            this.projectChangeData.createUserId == this.currentUserId
          )

          this.processInstanceId = this.projectChangeData.processInstanceId

          if (this.projectBuildData.projectClass == '64' && this.processInstanceId ) {
            this.showPrintBtn = true
          }
          
          this.budgetChangeContentList = this.projectChangeData.budgetChangeContent
            ? this.projectChangeData.budgetChangeContent.split(',')
            : []
          this.changeContentList = this.projectChangeData.changeContent
            ? this.projectChangeData.changeContent.split(',')
            : []
          if (
            this.projectBuildData.projectClass == '40' &&
            this.projectBuildData.projectMembers.indexOf(this.currentUserId) >= 0
          ) {
            if (this.changeContentList.indexOf('2') >= 0) {
              this.changeContentList.splice(this.changeContentList.indexOf('2'), 1)
            }
            if (this.changeContentList.indexOf('3') >= 0) {
              this.changeContentList.splice(this.changeContentList.indexOf('3'), 1)
            }
          }
          if (this.changeContentList.indexOf('6') >= 0) {
            this.changeContentList.splice(this.changeContentList.indexOf('6'), 1)
          }
          this.$emit('routerCallBack', this.changeContentList)
          this.getChangeInfluenceData()
          this.getChangeLogData()
          if (!this.changeId) {
            this.changeId = this.projectChangeData.id
            this.$router
              .replace({
                path:
                  '/projectbuildstup/changeRecord?projectBuildId=' +
                  this.projectBuildId +
                  '&pageId=8&changeFlag=true&changeId=' +
                  this.changeId,
              })
              .catch(() => {
                console.log('重定向出错')
              })
          }
        } else {
          if (
            ([2,3].indexOf(this.projectBuildData.status)<=-1) &&
            (this.projectBuildData.projectManagers.indexOf(this.currentUserId) >= 0 ||
              this.projectBuildData.assistantProjectManagers.indexOf(this.currentUserId) >= 0 ||
              this.projectBuildData.projectMembers.indexOf(this.currentUserId) >= 0 ||
              this.projectBuildData.submitUserId == this.currentUserId ||
              this.projectBuildData.projectSubTypeAdmin)
          ) {
            this.btnShow = true
          } else {
            this.btnShow = false
          }
        }
        if(this.budgetChangeContentList.indexOf('1') > -1){
        this.selectBudgetChangeContent = false
      }
        this.getChangeBudgetData()
      })
    },
    getChangeInfluenceData() {
      if (this.projectChangeData.id) {
        getAction(this.url.queryChangeInfluenceData, { changeId: this.projectChangeData.id }).then((res) => {
          this.influenceData = res.result || []
        })
      }
    },
    getChangeLogData() {
      if (this.projectChangeData.id) {
        getAction(this.url.queryChangeLog, { changeId: this.projectChangeData.id }).then((res) => {
          let changeLogs = res.result || []
          if (changeLogs.length > 0) {
            this.changeLogShow = true
          }
          this.baseInfoChangeLog = changeLogs.filter((l) => l.changeTarget === 1 ||  l.changeTarget === 101)
          this.timeChangeLog = changeLogs.filter((l) => l.changeTarget === 3)
          this.teamChangeLog = changeLogs.filter((l) => l.changeTarget === 4)
          let changeValueLog = changeLogs.filter((l) => l.changeTarget === 5)
          let changeCoreLog = changeLogs.filter((l) => l.changeTarget === 6)
          // this.attachChangeLog=changeLogs.filter(l=>l.changeTarget===7);
          if (this.baseInfoChangeLog.length > 0 || this.projectChangeData.status > 1) {
            this.changeContentOptions.filter((l) => l.value === '0')[0].disabled = true
          }
          if (this.timeChangeLog.length > 0 || this.projectChangeData.status > 1) {
            this.changeContentOptions.filter((l) => l.value === '1')[0].disabled = true
          }
          if (this.teamChangeLog.length > 0 || this.projectChangeData.status > 1) {
            this.changeContentOptions.filter((l) => l.value === '5')[0].disabled = true
          }
          // if(this.attachChangeLog.length>0||this.projectChangeData.status>1){
          //   this.changeContentOptions.filter(l=>l.value==='6')[0].disabled=true;
          // }
          if (changeValueLog.length > 0 || this.projectChangeData.status > 1) {
            this.changeContentOptions.filter((l) => l.value === '2')[0].disabled = true
          }
          if (changeCoreLog.length > 0 || this.projectChangeData.status > 1) {
            this.changeContentOptions.filter((l) => l.value === '3')[0].disabled = true
          }
          changeValueLog = changeValueLog.concat(changeCoreLog)
          changeValueLog.sort(function (a, b) {
            return b.id - a.id
          })

          this.valueTestChangeLog = changeValueLog
          if (this.valueTestChangeLog.length > 0) {
            this.getChangeLevelInfo()
          }
        })
      }
    },
    getChangeBudgetData() {
      const that = this
      that.budgetGroups = []
      getAction(this.url.queryChangeBudgetItemById, {
        buildId: this.projectBuildData.id,
        changeId: this.projectChangeData.id,
      }).then((res) => {
        // let changeBudgetItemList = res.result || []
        // if (changeBudgetItemList.length > 0) {
        //   let budgetGroups = that.groupBy(changeBudgetItemList, (item) => {
        //     return item.factoryCode
        //   })
        //   budgetGroups.forEach(function (budgetList) {
        //     let group = {}
        //     let budgetItem = budgetList[0]
        //     group.factoryCode = budgetItem.factoryCode
        //     group.factory = budgetItem.factory
        //     group.factoryName = budgetItem.factoryName
        //     group.costCenterNo = budgetItem.costCenterNo
        //     group.budgetList = budgetList
        //     that.budgetGroups.push(group)
        //   })
        //   console.info(budgetGroups)
        // }
        this.budgetItemTree=res.result || [];
        this.countChangeTotal()
      })
    },
    groupBy(array, f) {
      const groups = {}
      array.forEach(function (o) {
        const group = JSON.stringify(f(o))
        groups[group] = groups[group] || []
        groups[group].push(o)
      })
      return Object.keys(groups).map(function (group) {
        return groups[group]
      })
    },
    countChangeTotal() {
      let originTotal = 0,
        changeTotal = 0,
        historyTotal = 0;
      // this.budgetGroups.forEach(function (group) {
      //   group.budgetList.forEach(function (item) {
      //     originTotal += parseFloat(item.originAmount)
      //     changeTotal += parseFloat(item.changeAmount)
      //     historyTotal += parseFloat(item.historyChangeAmount)
      //   })
      // })
      this.budgetItemTree.forEach(function (item) {
              originTotal += parseFloat(item.originAmount);
              changeTotal += parseFloat(item.changeAmount);
              historyTotal += parseFloat(item.historyChangeAmount);
            });
      this.totalAmount = parseFloat(originTotal.toFixed(2)).toLocaleString()
      this.totalTenThousand = parseFloat((originTotal / 10000).toFixed(2)).toLocaleString()
      this.totalAmountChange = parseFloat(changeTotal.toFixed(2)).toLocaleString()
      this.totalTenThousandChange = parseFloat((changeTotal / 10000).toFixed(2)).toLocaleString()
      this.amountHistory = parseFloat(historyTotal.toFixed(2)).toLocaleString()
      this.amountHistoryTenThousand = parseFloat((historyTotal / 10000).toFixed(2)).toLocaleString()
    },
    getChangeLevelInfo() {
      getAction(this.url.queryChangeLevelInfo, { changeId: this.projectChangeData.id }).then((res) => {
        if (res.result) {
          this.originLevelData = res.result.originLevel
          this.changeLevelData = res.result.changeLevel
        }
      })
    },
    addInfluence() {
      let addRow = {
        id: '',
        projectChangeId: '',
        deptId: '',
        deptName: '',
        userId: '',
        userName: '',
        isSendTask: false,
      }
      this.influenceData.push(addRow)
    },
    selectUser(record) {
      this.limit = 0
      this.selectUserType = 'influence'
      this.currentRecord = record
      this.originTargetKeys = record.userId ? record.userId.split(',') : []
      this.$refs.userSelect.doSelect()
    },
    selectDutyUser() {
      this.limit = 1
      this.selectUserType = 'duty'
      this.originTargetKeys = []
      this.$refs.userSelect.doSelect()
    },
    setResult(result) {
      if (this.selectUserType === 'duty') {
        this.projectChangeData.dutyUserId = result[0].username
        this.projectChangeData.dutyUserName = result[0].realname
      } else {
        let selectUserId = [],
          selectUserName = []
        result.forEach(function (user) {
          selectUserId.push(user.username)
          selectUserName.push(user.realname)
        })
        this.currentRecord.userId = selectUserId.join(',')
        this.currentRecord.userName = selectUserName.join(',')
      }
    },
    delInfluenceData() {
      if (this.selectedRow.length === 0) {
        this.$message.warning('请先选择要删除的行')
        return
      }

      const that = this
      Modal.confirm({
        title: '提示',
        content: '确定删除选中的影响模块？',
        onOk() {
          //使用index倒序删除
          that.selectedRowKeys
            .sort((a, b) => {
              return b - a
            })
            .forEach(function (row) {
              that.influenceData.splice(row, 1)
            })
          that.selectedRow = []
          that.selectedRowKeys = []
          that.$message.success('删除成功，保存生效')
        },
        onCancel() {},
      })
    },
    addFactory() {
      if (this.budgetChangeContentList.indexOf('3') < 0) {
        this.$message.warning('请勾选预算变更内容-费用支出公司变更')
        return
      }
      this.selectFactoryData = {};
      this.addCostCenterNo="";
      this.showAddFactory = true
    },
    openFactorySelector() {
      this.$refs.FactorySelector.openInit({ returnParam: { type: 'add' } })
    },
    selectFactorySelector(item, returnParam) {
      if (returnParam.type == 'add') {
        this.selectFactoryData = item
        this.$set(this.selectFactoryData, 'name', item.name)
      }
    },
    selectCostCenter() {
      if(this.showAddFactory){
        if (!this.selectFactoryData.parentid) {
          this.$message.warning('请选择费用支出公司')
          return
        }
        this.costCenterData.params.companyCode = this.selectFactoryData.parentid
      }
      if(this.showChangeCenter){
        this.costCenterData.params.companyCode = this.selectedBudgetItemRows[0].factoryCode;
      }
      this.$refs.costCenterSelect.open()
    },
    costCenterHandleOk(costCenterData){
      this.addCostCenterNo=costCenterData[0].costCenter;
      this.$refs.costCenterSelect.close()
    },
    doAddFactory() {
      let vm=this;
      // let checkData = this.budgetGroups.filter((b) => b.factoryCode === this.selectFactoryData)
      let checkData=[];
      this.budgetItemTree.forEach(root=>{
        checkData=checkData.concat(root.children.filter((b) => b.factoryCode === vm.selectFactoryData.parentid));
      });
      if (checkData && checkData.length > 0) {
        this.$message.warning('已存在费用支出公司【' + checkData[0].factoryName + '】预算，不能重复添加')
        return
      }
      if(!this.addCostCenterNo||this.addCostCenterNo.trim()===''){
        this.$message.warning('成本中心号必填')
        return
      }
      let factory = this.factoryData.filter((f) => f.parentid.trim() === this.selectFactoryData.parentid)[0]
      // let factoryCode = this.selectFactoryData.substring(0, 2)
      // let costCenterNoReg = null
      // eval(' costCenterNoReg= /^' + factoryCode + '\\d+((,' + factoryCode + '\\d+)*)?$/;')
      //
      // if (!costCenterNoReg.test(this.addCostCenterNo)) {
      //   this.$message.warning(
      //     '费用支出公司 [' +
      //     factory.name.trim() +
      //     '] 成本中心号必须以代码的前2位开头，只能填写数字，多个成本中心号英文逗号[,]分隔'
      //   )
      //   return;
      // }
      //考虑有新旧预算同时存在的情况
      let root={
        wbsConcat:vm.projectBuildData.projectNo,
        wbsName:vm.projectBuildData.projectName,
        wbsLevel:1,
        children:[]
      };
      if(this.budgetItemTree&&this.budgetItemTree.length>0){
        root=this.budgetItemTree.filter(b=>b.wbsConcat==vm.projectBuildData.projectNo)[0];
      }
      let second={
        id: '',
        wbsName:vm.projectBuildData.projectName,
        wbsLevel:2,
        wbsConcat:root.wbsConcat+"."+factory.code.trim(),
        originAmount:0,
        changeAmount: '0',
        historyChangeAmount: '0',
        costType:'',
        factory: factory.code.trim(),
        factoryName: factory.name.trim(),
        factoryCode: factory.parentid,
        costCenterNo: vm.addCostCenterNo,
        budgetItem:null,
        status:'新增',
        parentCode:root.wbsConcat,
        children:[],
      };
      this.budgetItemData.forEach(function (item) {
        let budget = {
          id: '',
          factory: factory.code.trim(),
          factoryName: factory.name.trim(),
          factoryCode: factory.parentid,
          costCenterNo: vm.addCostCenterNo,
          originAmount: '0',
          memo: '',
          changeAmount: '0',
          historyChangeAmount: '0',
          projectBudgetCode: item.code.trim(),
          budgetItem: item.name.trim(),
          wbsName:vm.projectBuildData.projectName+"-"+item.name.trim(),
          wbsLevel:3,
          wbsConcat:root.wbsConcat+"."+factory.code.trim()+"."+item.parentid.trim(),
          costType:item.additionalField,
          status:'新增',
          parentCode:second.wbsConcat,
          children:[],
        }
        second.children.push(budget)
      })
      root.children.push(second);
      if(!this.budgetItemTree||this.budgetItemTree.length===0){
        this.budgetItemTree=[];
        this.budgetItemTree.push(root)
      }
      this.showAddFactory = false
    },
    cancelAddFactory() {
      this.showAddFactory = false
    },
    changeCostCenter(){
      if(!this.selectedBudgetItemRows||this.selectedBudgetItemRows.length===0){
        this.$message.warning('请选择需要修改成本中心的数据！');
        return;
      }
      let factoryCode=this.selectedBudgetItemRows[0].factoryCode;
      let flag=this.selectedBudgetItemRows.some(row=> row.factoryCode!==factoryCode);
      if(flag){
        this.$message.warning('只能选择同一公司的数据进行修改！');
        return;
      }
      this.addCostCenterNo='';
      this.showChangeCenter=true;
    },
    doChangeCenter(){
      const vm=this;
      if (!this.addCostCenterNo && this.addCostCenterNo.trim() === '') {
        this.$message.warning('请选择成本中心号');
        return
      }
      this.budgetItemTree.forEach(root=>{
        root.children.forEach(second=>{
          if(vm.selectedBudgetItemRowKeys.indexOf(second.wbsConcat)>=0){
            let originCostCenterNo=second.originCostCenterNo?second.originCostCenterNo:second.costCenterNo;
            second.costCenterNo=vm.addCostCenterNo;
            if(originCostCenterNo===vm.addCostCenterNo||second.status=='新增'){
              second.originCostCenterNo='';
            }else{
              second.originCostCenterNo=originCostCenterNo;
            }
          }
          if(second.children&&second.children.length>0){
            second.children.forEach(third=>{
              if(vm.selectedBudgetItemRowKeys.indexOf(third.wbsConcat)>=0){
                let originCostCenterNo=third.originCostCenterNo?third.originCostCenterNo:third.costCenterNo;
                third.costCenterNo=vm.addCostCenterNo;
                if(originCostCenterNo===vm.addCostCenterNo||third.status=='新增'){
                  third.originCostCenterNo='';
                }else{
                  third.originCostCenterNo=originCostCenterNo;
                }
              }
              if(third.children&&third.children.length>0){
                third.children.forEach(fourth=>{
                  if(vm.selectedBudgetItemRowKeys.indexOf(fourth.wbsConcat)>=0){
                    let originCostCenterNo=fourth.originCostCenterNo?fourth.originCostCenterNo:fourth.costCenterNo;
                    fourth.costCenterNo=vm.addCostCenterNo;
                    if(originCostCenterNo===vm.addCostCenterNo||fourth.status=='新增'){
                      fourth.originCostCenterNo='';
                    }else{
                      fourth.originCostCenterNo=originCostCenterNo;
                    }
                  }
                })
              }
            })
          }
        });
      })
      this.selectedBudgetItemRows=[];
      this.selectedBudgetItemRowKeys=[];
      this.showChangeCenter=false;
    },
    delBudgetItem() {
      if (this.budgetChangeContentList.indexOf('3') < 0) {
        this.$message.warning('请勾选预算变更内容-费用支出公司变更')
        return
      }
      if (this.selectedBudgetItemRowKeys.length === 0) {
        this.$message.warning('请先选择要删除的行')
        return
      }

      const that = this
      Modal.confirm({
        title: '提示',
        content: '确定删除选中的变更预算项？',
        onOk() {
          that.selectedBudgetItemRowKeys.forEach(function (key) {
            /*that.budgetGroups.forEach(function (item, index) {
              if (item.factoryCode === key) {
                that.budgetGroups.splice(index, 1)
              }
            })*/
            that.budgetItemTree.forEach(root=>{
              root.children.forEach((second, index)=>{
                if(second.wbsConcat==key){
                  root.children.splice(index, 1)
                }
              })
            })
          })
          that.$message.success('删除成功，保存生效')
        },
        onCancel() {},
      })
    },
    checkChangeContent(submit) {
      if (this.budgetChangeContentList.length > 0) {
        this.projectChangeData.changeTotal = !this.projectChangeData.changeTotal
          ? '0'
          : this.projectChangeData.changeTotal
        this.projectChangeData.addToSapTotal = !this.projectChangeData.addToSapTotal
          ? '0'
          : this.projectChangeData.addToSapTotal
        if (
          submit &&
          (this.projectChangeData.changeTotal.toString() === '' ||
            this.projectChangeData.addToSapTotal.toString() === '')
        ) {
          this.$message.warning('本次变更费用和追加至SAP系统费用必填')
          return false
        }
        let changeTotal = parseFloat(this.projectChangeData.changeTotal)
        if (this.projectChangeData.changeTotal.toString() !== '' && isNaN(changeTotal)) {
          this.$message.warning('请正确输入本次变更费用')
          return false
        }
        let addToSapTotal = parseFloat(this.projectChangeData.addToSapTotal)
        if (this.projectChangeData.addToSapTotal.toString() !== '' && isNaN(addToSapTotal)) {
          this.$message.warning('请正确输入加至SAP系统费用')
          return false
        }
        let changeAmountTotal = 0
        this.changeBudgetItemData = []
        /*for (let i = 0; i < this.budgetGroups.length; i++) {
          let group = this.budgetGroups[i]
          let factoryName = group.factoryName
          if (submit) {
            let factoryCode = group.factoryCode.substring(0, 2)
            let costCenterNoReg = null
            eval(' costCenterNoReg= /^' + factoryCode + '\\d+((,' + factoryCode + '\\d+)*)?$/;')

            if (!costCenterNoReg.test(group.costCenterNo)) {
              this.$message.warning(
                '费用支出公司 [' +
                  factoryName +
                  '] 成本中心号必须以代码的前2位开头，只能填写数字，多个成本中心号英文逗号[,]分隔'
              )
              return false
            }
          }
          for (let j = 0; j < group.budgetList.length; j++) {
            let item = group.budgetList[j]
            if (submit && item.changeAmount.toString() === '') {
              this.$message.warning(
                '请输入费用支出公司【' + factoryName + '】预算项【' + item.budgetItem + '】变更费用'
              )
              return false
            }
            let changeAmount = parseFloat(item.changeAmount)
            if (isNaN(changeAmount)) {
              this.$message.warning(
                '请正确输入费用支出公司【' + factoryName + '】预算项【' + item.budgetItem + '】变更费用'
              )
              return false
            }
            item.factoryName = factoryName
            item.factoryCode = group.factoryCode
            item.factory = group.factory
            item.costCenterNo = group.costCenterNo
            changeAmountTotal += changeAmount
          }
          this.changeBudgetItemData = this.changeBudgetItemData.concat(group.budgetList)
        }*/
        this.budgetItemTree.forEach(root=>{
          root.children.forEach(second=>{
            if(second.children&&second.children.length>0){
              second.children.forEach(third=>{
                if(third.children&&third.children.length>0){
                  third.children.forEach(item=>{
                    changeAmountTotal += parseFloat(item.changeAmount)
                  })
                }else{
                  changeAmountTotal += parseFloat(third.changeAmount)
                }
              })
            }else{
              changeAmountTotal += parseFloat(second.changeAmount)
            }
          })
        });

        if (submit && addToSapTotal.toFixed(2) !== changeAmountTotal.toFixed(2)) {
          this.$message.warning('各分项变更费用求和不等于追加SAP费用，请核对。')
          return false
        }
      }
      return true
    },
    save(event) {
      this.btnLoading = true
      this.projectChangeData.projectBuildId = this.projectBuildId
      this.projectChangeData.influenceList = this.influenceData
      this.projectChangeData.changeContent = this.changeContentList.join(',')
      this.projectChangeData.budgetChangeContent = this.budgetChangeContentList.join(',')
      if (!this.checkChangeContent(false)) {
        this.btnLoading = false
        return
      }
      this.projectChangeData.changeBudgetItemList =
        // this.budgetChangeContentList.length > 0 ? this.changeBudgetItemData : null
        this.budgetChangeContentList.length > 0 ? this.budgetItemTree : null
      this.projectChangeData.changeAmount =
        this.budgetChangeContentList.length > 0 ? this.projectChangeData.changeAmount : ''
      this.projectChangeData.addToSapTotal =
        this.budgetChangeContentList.length > 0 ? this.projectChangeData.addToSapTotal : ''
      postAction(this.url.saveChange, this.projectChangeData)
        .then((res) => {
          this.btnLoading = false
          if (res.success) {
            if(!event.autoSave){
              this.$message.success('保存成功');
            }
            if (!this.changeId) {
              this.$router
                .replace({
                  path:
                    '/projectbuildstup/changeRecord?projectBuildId=' +
                    this.projectBuildId +
                    '&pageId=8&changeFlag=true&changeId=' +
                    res.result,
                })
                .catch(() => {
                  console.log('重定向出错')
                })
            }
            this.changeId = res.result
            this.getProjectChangeData()
          } else {
            this.$message.warning('保存失败:' + res.message)
          }
        })
        .catch((res) => {
          this.btnLoading = false
          this.$message.warning('保存失败:' + res.message)
        })
    },
    del() {
      const that = this
      Modal.confirm({
        title: '提示',
        content: '确定删除变更单？',
        onOk() {
          that.btnLoading = true
          getAction(that.url.delChange, { id: that.projectChangeData.id })
            .then((res) => {
              that.btnLoading = false
              if (res.success) {
                that.$message.success('删除成功')
                setTimeout(() => {
                  window.CloseCefTab ? window.CloseCefTab() : window.close()
                }, 1000)
              } else {
                that.$message.warning('删除失败:' + res.message)
              }
            })
            .catch((res) => {
              that.btnLoading = false
              that.$message.warning('删除失败:' + res.message)
            })
        },
        onCancel() {},
      })
    },
    onSubmit1() {
      if(this.projectChangeData.createUserId != this.currentUserId){
        this.$message.warning('非本人创建的变更单不能提交');
        return;
      }
      const that = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!this.checkChangeContent(true)) {
            return
          }
          if (this.projectBuildData.projectClass === '40') {
            this.projectChangeData.projectBuildId = this.projectBuildId //立项ID
            this.projectChangeData.influenceList = this.influenceData //影响模块列表
            this.projectChangeData.changeContent = this.changeContentList.join(',') //其他变更内容
            this.projectChangeData.budgetChangeContent = this.budgetChangeContentList.join(',') //预算变更内容
            this.projectChangeData.changeBudgetItemList =
              // this.budgetChangeContentList.length > 0 ? this.changeBudgetItemData : null // 预算变更分项
              this.budgetChangeContentList.length > 0 ? this.budgetItemTree : null // 预算变更分项
            this.projectChangeData.changePercent = this.changePercent //累计变更金额百分比
            this.projectChangeData.budgetGroups = this.budgetGroups
            console.info(this.changeBudgetItemData)
            console.info(this.projectChangeData)
            postAction(this.url.calcChangeRecordFlow, this.projectChangeData).then((res) => {
              if (res.success) {
                let flow = res.result
                this.$refs.processUserSelect1.open(flow)
              }
            })
          } else {
            if (this.projectBuildData.projectClass === '64') {
              this.selUserCols = this.company64UserCols
            } else {
              this.selUserCols = this.otherUserCols
            }
            if (this.changeContentList && this.changeContentList.indexOf('1') >= 0) {
              this.checkProjectCycleRules()
            } else {
              that.$refs.processUserSelect.doSelect()
            }
          }
        } else {
          document.getElementById('projectChangeNo').scrollIntoView()
          return false
        }
      })
    },
    onSubmit() {
      const that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let userNameArr = [],
            realNameArr = []
          for (let i = 0; i < that.influenceData.length; i++) {
            let item = that.influenceData[i]
            let checkData = that.influenceData.filter((i) => i.deptName === item.deptName)
            if (checkData.length > 1) {
              that.$message.warning('影响模块部门【' + item.deptName + '】重复')
              return false
            }
            userNameArr.push(item.userId)
            realNameArr.push(item.userName)
          }
          if (that.projectBuildData.projectClass === '40') {
            if (that.projectChangeData.changeType === '土建') {
              that.selUserCols = this.civilEngineeringUserCols
            } else {
              that.selUserCols = this.engineeringUserCols
            }
            if (userNameArr.length > 0) {
              that.selUserCols.forEach(function (item) {
                if (item.field === 'disciplineLeaderSupervisorUser') {
                  item.username = userNameArr.join(',')
                  item.realname = realNameArr.join(',')
                }
              })
            }
          } else {
            that.selUserCols = this.otherUserCols
          }
          if (!this.checkChangeContent(true)) {
            return
          }
          if (this.changeContentList && this.changeContentList.indexOf('1') >= 0) {
            this.checkProjectCycleRules()
          } else {
            that.$refs.processUserSelect.doSelect()
          }
        } else {
          document.getElementById('projectChangeNo').scrollIntoView()
          return false
        }
      })
    },
    checkProjectCycleRules() {
      let vm = this
      getAction(this.url.checkChangeCycleRules, { changeId: this.changeId }).then((res) => {
        if (res.code == 200) {
          if (res.result && res.result !== '') {
            let checkResult=JSON.parse(res.result);
            const h = this.$createElement;
            const m = checkResult.message.split('；');
            let html = [];
            html.push(h('div', "按项目周期管理要求："));
            m.forEach(item =>{
              html.push(h('div', item))
            });
            if(checkResult.forceCanNotSubmit){
              this.$info({
                title: '周期规则校验结果',
                content:  h('div', {}, html),
                onOk() {},
              });
            }else{
              html.push(h('div', "确定提交变更单？"));
              Modal.confirm({
                title: '周期规则校验结果',
                content:  h('div', {}, html),
                onOk() {
                  vm.projectChangeData.overdueProject = true;
                  vm.$refs.processUserSelect.doSelect()
                },
                onCancel() {},
              })
            }
          } else {
            vm.projectChangeData.overdueProject = false
            vm.$refs.processUserSelect.doSelect()
          }
        } else {
          this.$message.warning('校验项目周期规则异常:' + res.message)
        }
      })
    },
    selectUserConfirm(cols) {
      if (!cols || cols.length === 0) {
        this.$message.warning('没有选择审批人')
        return
      }
      this.btnLoading = true
      let data = {}
      cols.forEach((item) => {
        let key = item.field
        data[key] = item.username
      })

      if (this.projectBuildData.projectClass !== '40' && this.influenceData.length > 0) {
        let userNameArr = []
        this.influenceData.forEach(function (item) {
          userNameArr.push(item.userId)
        })
        data.disciplineLeaderSupervisorUser = userNameArr.join(',')
      }
      this.projectChangeData.approvalPerson = data
      this.projectChangeData.projectBuildId = this.projectBuildId
      this.projectChangeData.influenceList = this.influenceData
      this.projectChangeData.changeContent = this.changeContentList.join(',')
      this.projectChangeData.budgetChangeContent = this.budgetChangeContentList.join(',')
      this.projectChangeData.changeBudgetItemList =
        // this.budgetChangeContentList.length > 0 ? this.changeBudgetItemData : null
        this.budgetChangeContentList.length > 0 ? this.budgetItemTree : null
      this.projectChangeData.changeAmount =
        this.budgetChangeContentList.length > 0 ? this.projectChangeData.changeAmount : ''
      this.budgetChangeContentList.length > 0 ? this.projectChangeData.addToSapTotal : ''
      this.projectChangeData.changePercent = this.changePercent //累计变更金额百分比
      postAction(this.url.submitChange, this.projectChangeData)
        .then((res) => {
          this.btnLoading = false
          if (res.success) {
            this.$emit('routerCallBack', this.changeContentList)
            this.$message.success('提交成功')
            this.getProjectChangeData()
          } else {
            this.$message.warning('提交失败:' + res.message)
          }
        })
        .catch((res) => {
          this.btnLoading = false
          this.$message.warning('提交失败:' + res.message)
        })
    },
    selectUserConfirm1(flow) {
      if (!flow) {
        return
      }
      flow.buildId = this.projectBuildId
      flow.changeId = this.changeId
      postAction(this.url.startProcessFlow, flow).then((res) => {
        if (res.success) {
          this.$message.success('提交成功')
          this.$router.go(0)
        } else {
          this.$message.error('提交失败:' + res.message)
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRows
    },
    onSelectBudgetItemChange(selectedRowKeys,selectedRows) {
      this.selectedBudgetItemRowKeys = selectedRowKeys;
      this.selectedBudgetItemRows=selectedRows;
    },
    onSelectOriginItemChange(selectedRowKeys, selectedRows) {
      this.selectBudgetItem.selectedRowKeys = selectedRowKeys
      this.selectBudgetItem.selectedRows = selectedRows
    },
    checkInputMoney(event) {
      let valueStr = event.target.value
      if (valueStr !== '') {
        let value = parseFloat(valueStr)
        if (isNaN(value)) {
          this.$message.warning('请正确输入预算金额')
          return
        }
        if (value < 1000 || value > 10000000) {
          this.$info({
            title: '提示',
            content: '费用金额单位为元，填写时请注意',
            onOk() {},
          })
        }
      }
    },
    projectReserve() {
      let urlJump = this.$router.resolve({ path: '/projectBuildReserve?projectBuildId=' + this.projectBuildData.id })
      window.open(urlJump.href, '_blank')
    },
    projectChangeHistory() {
      // window.open('/changehistory?projectBuildId='+this.projectBuildData.id);
      this.showHistoryList = true
    },
    changeContentChange(checkValue) {
      //选择价值表、核心力值表，默认选择团队表
      if ((checkValue.indexOf('2') >= 0 || checkValue.indexOf('3') >= 0) && this.changeContentList.indexOf('5') < 0) {
        this.changeContentList.push('5')
      }
      const vm=this;
      this.changeContentList.forEach(c=>{
        if (!vm.projectChangeData.changeContent) {
          let tabName=vm.changeContentOptions.filter(o=>{return c==o.value})[0].label;
          vm.$message.warning('请在【'+tabName+'】分页界面上填写变更信息');
        }
        if(vm.projectChangeData.changeContent && vm.projectChangeData.changeContent.indexOf(c)<0){
          let tabName=vm.changeContentOptions.filter(o=>{return c==o.value})[0].label;
          vm.$message.warning('请在【'+tabName+'】分页界面上填写变更信息');
        }
      });
      this.save({autoSave:true});
    },
    selectFactoryChange(value, group) {
      let factoryItem = this.factoryData.filter((item) => item.parentid === value)[0]
      let checkData = this.budgetGroups.filter((group) => group.factoryCode == value)
      if (checkData.length > 1) {
        this.$message.warning('已存在费用支出公司【' + factoryItem.name.trim() + '】预算')
        factoryItem = this.factoryData.filter((item) => item.code.trim() === group.factory)[0]
        group.factoryCode = factoryItem.parentid
        return
      }
      group.factory = factoryItem.code.trim()
      group.factoryCode = value
      group.factoryName = factoryItem.name.trim()
    },
    changeAmountChange(event, record) {
      let valueStr = event.target.value
      let value = 0
      if (valueStr.toString() !== '') {
        value = parseFloat(valueStr.toString())
        if (isNaN(value)) {
          this.$message.warning('请正确输入变更费用')
        }
        record.changeAmount = value
      }
      this.countChangeAmount()
    },
    countChangeAmount() {
      let changeTotal = 0
      // this.budgetGroups.forEach(function (group) {
      //   group.budgetList.forEach(function (item) {
      //     changeTotal += parseFloat(item.changeAmount)
      //   })
      // })
      this.budgetItemTree.forEach(root=>{
        root.children.forEach(second=>{
          if(second.children&&second.children.length>0) {
            second.children.forEach(third => {
              if (third.children && third.children.length > 0) {
                third.children.forEach(item => {
                  changeTotal += parseFloat(item.changeAmount)
                })
              } else {
                changeTotal += parseFloat(third.changeAmount)
              }
            })
          }
        })
      });
      this.totalAmountChange = parseFloat(changeTotal.toFixed(2)).toLocaleString()
      this.totalTenThousandChange = parseFloat((changeTotal / 10000).toFixed(2)).toLocaleString()
    },
    /*===========附件方法======================*/
    attachDataListFresh() {
      this.attachmentDataList = []
      this.attachmentData.forEach((item) => {
        let size = formatFileSize(item.size)
        this.attachmentDataList.push({
          key: item.id,
          fileName: item.fileName,
          size: size,
          uploadTime: item.uploadTime,
          uploader: item.uploader,
          uploaderName: item.uploaderName,
        })
      })
    },
    showAttach(id, uploader, fileName, autoDownload) {
      if (!this.checkPermisson(uploader)) {
        this.$message.warning('仅有该附件上传人、审批人、抄送人、项目经理、副经理可以查看!')
        return
      }
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        if (autoDownload) {
          this.doDownLoadBatch(id)
          return
        }
        this.$message.warning('该附件类型不支持预览，请下载附件查看')
        return
      }
      let params={
        id:id,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        if (this.projectBuildData.projectClass == '40' || this.projectBuildData.projectClass == '61') {
          window.open(process.env.BASE_URL+'/pdf/web/normalViewer.html?file=' + url)
        } else {
          window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
        }
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    checkPermisson(uploader) {
      let currUser = Vue.ls.get(USER_NAME)
      return uploader == currUser || this.downloadAndView
    },
    onSelectAttachChange(selectedRowKeys, selectedRows) {
      this.selectedAttachRowKeys = selectedRowKeys
      this.selectedAttachRows = selectedRows
    },
    downLoadBatch() {
      if (this.selectedAttachRowKeys != null && this.selectedAttachRowKeys.length > 0) {
        this.doDownLoadBatch(this.selectedAttachRowKeys)
      } else {
        this.$message.warning('请选择要下载的其它附件')
      }
    },
    deleteBatch() {
      const that = this
      if (this.selectedAttachRowKeys != null && this.selectedAttachRowKeys.length > 0) {
        for(let row of this.selectedAttachRows){
          if(row.uploader!=this.currentUserId){
            return this.$message.warning('请勿删除非本人上传的附件')
          }
        }
        Modal.confirm({
          title: '提示',
          content: '确定删除选中的附件？',
          onOk() {
            that.delFiles(that.selectedAttachRowKeys.join(','))
          },
          onCancel() {},
        })
      } else {
        this.$message.warning('请选择要删除的其它附件')
      }
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        let downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      let iframe = document.getElementById('_attachToolView_downloadfile_frame')
      let href =
        this.API_BASE_URL +
        this.attach.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)
      iframe.src = href
    },
    delFiles(attachIds) {
      const json = { dbKey: 'Trd', id: attachIds, ftpKey: 'ftp' }
      this.$refs.myUpload.delete(json)
    },
    /*===========流程引擎回调方法======================*/
    beforeSubmit(res) {
      // 提交前置动作
      console.log('beforeSubmit')
      const vm = this
      if (
        (this.currentNodeDefKey === 'costDepartment' || this.currentNodeDefKey === 'costDepartmentSupervisor') &&
        this.projectBuildData.projectClass === '40' &&
        this.projectChangeData.changeType === '土建'
      ) {
        if (!this.projectChangeData.costAuditRemark || this.projectChangeData.costAuditRemark.trim() === '') {
          this.$message.warning('请输入造价员审核结论')
          document.getElementById('costAuditRemark').scrollIntoView()
          return false
        } else {
          postAction(this.url.saveCostAuditRemark, this.projectChangeData)
            .then((res) => {
              if (res.success) {
                vm.$refs.childrenRef.submitTaskNotBefore()
              } else {
                this.$message.warning('保存造价员审核结论失败:' + res.message)
              }
            })
            .catch((res) => {
              this.$message.warning('保存造价员审核结论失败:' + res.message)
            })
        }
        return false
      }
      // if(this.budgetChangeContentList.length>0){
      //   this.$set(this.custom, 'isUpper', this.isUpper+"")
      //   this.$set(this.custom, 'changePercent', this.changePercent+"")
      // }else{
      //   this.$set(this.custom, 'isUpper', "0")
      //   this.$set(this.custom, 'changePercent', this.changePercent+"")
      // }
      // console.info(this.custom)
      return true
    },
    beforeReject(res) {
      // 驳回前置动作
      if (this.checkOptionValue()) {
        // return this.doAuditNotPass()
        return true
      } else {
        return false
      }
    },
    taskLoad(task) {
      debugger
      // 当前任务加载回调函数，获取当前任务信息
      this.currentNodeDefKey = task.taskDefKey
    },
    //-------------流程回调------end
    doAuditPass() {
      let flag = false
      postAction(this.url.auditPass, {
        id: this.projectChangeData.id,
        costAuditRemark: this.projectChangeData.costAuditRemark,
      }).then((res) => {
        if (res.code == 200) {
          flag = true
        } else {
          this.$message.warning('流程审批通过接口异常:' + res.message)
        }
      })
      return flag
    },
    async doAuditNotPass() {
      let flag = false
      await getActionAsync(this.url.auditNotPass, { changeId: this.projectChangeData.id }).then((res) => {
        if (res.code == 200) {
          flag = true
          this.$router.go(0)
        } else {
          this.$message.warning('流程审批不通过接口异常:' + res.message)
        }
      })
      return flag
    },
    doAuditBack(backKey) {
      let flag = false
      getAction(this.url.auditBack, { changeId: this.projectChangeData.id, backKey: backKey }).then((res) => {
        if (res.code == 200) {
          flag = true
          this.$router.go(0)
        } else {
          this.$message.warning('流程审批退回接口异常:' + res.message)
        }
      })
      return flag
    },
    async doAuditCancel() {
      let flag = false
      await getActionAsync(this.url.auditCancel, { changeId: this.projectChangeData.id }).then((res) => {
        if (res.code == 200) {
          flag = true
        } else {
          this.$message.warning('流程审批退回接口异常:' + res.message)
        }
      })
      return flag
    },
    checkOptionValue() {
      let options = this.$refs.childrenRef.data
      if (options == '' || options == null || options == undefined) {
        this.$message.warning('请输入审批意见')
        return false
      } else {
        return true
      }
    },
    print() {
      ++this.printKey;
      console.log(this.projectBuildData)
      console.log(this.projectChangeData)
      console.log(this.changeId)
      this.printModalShowFlag = true
      // window.open("/projectChangePrint?changeId="+this.changeId+"&projectNo="
      // +this.projectBuildData.projectNo+"&projectName="+this.projectBuildData.projectName
      // +"&deptName="+this.projectChangeData.dutyDeptName+"&userName="+this.projectChangeData.dutyUserName
      // +"&buildId="+this.projectBuildId)
    },
    changeBudgetChangeContentList() {
      if (this.budgetChangeContentList.indexOf('1') > -1 && !this.selectBudgetChangeContent) {
        this.selectBudgetChangeContent = true
        Modal.confirm({
          title: '项目总预算调整',
          content:
            '当项目预算总额满足项目变更范围时，不得申请追加总预算，如子项预算费用不足，可通过项目内预算变更来调整项目子项预算。',
          onOk() {},
          onCancel() {}
        })
      }else{
        this.selectBudgetChangeContent =false
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-table-tbody .ant-select-selection {
  border-radius: unset;
  border: unset;
}
/deep/ .ant-btn-primary {
  background: #4095e4;
}
/deep/ .ant-btn {
  border-radius: unset;
}
/deep/ .ant-table-thead > tr > th {
  background: #dadee9 !important;
}
/deep/.ant-table-small,
/deep/.ant-table-thead > tr:first-child > th:first-child,
/deep/.ant-table-thead > tr:first-child > th:last-child {
  border-radius: unset;
}
/deep/.ant-table-thead > tr > th,
/deep/.ant-table-tbody > tr > td,
/deep/.ant-table-tbody .ant-table-row td {
  padding: 10px 16px;
}
/deep/.ant-card-small > .ant-card-head {
  background: #f6f7f9;
}
/deep/.ant-collapse > .ant-collapse-item > .ant-collapse-header {
  border-radius: unset;
  padding: 8px 32px;
  background: #f6f7f9;
}
/deep/.ant-collapse > .ant-collapse-item > .ant-collapse-content {
  height: 250px;
  overflow-y: scroll;
}
/deep/.ant-timeline-item-content {
  display: flex;
  justify-content: space-between;
  > div:last-child {
    min-width: 9vw;
    text-align: right;
    color: #999;
  }
}
.process-engine {
  /deep/ #process-container {
    width: unset !important;
  }
  /deep/ #process-container .process-item .info-fullMessage {
    max-width: 1200px;
  }
}
#change-record {
  border: 1px solid #e6e6e6;
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 55px;
  h4 {
    font-weight: bolder;
    display: inline-block;
    position: relative;
    padding-left: 13px;
    &:before {
      content: '';
      position: absolute;
      display: inline-block;
      top: 5%;
      left: 0;
      background-color: #47a4fa;
      width: 3px;
      height: 90%;
    }
  }
  .container {
    // margin:30px 125px 0;
    height: inherit;
    .title {
      display: flex;
      justify-content: center;
      margin-bottom: 15px;
      h3 {
        font-size: 18px;
        font-weight: 600;
        margin-right: 25px;
      }
      .icon-plus {
        font-size: 13px;
        padding-right: 5px;
      }
    }
    .content {
      background-color: #fff;
      // border: 1px solid #eaeaea;
      .tip-head {
        padding: 11px 19px 0px;
        position: relative;
        top: 3px;
      }
      .content-title {
        border-bottom: 1px solid #f2f2f2;
        padding: 15px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .header {
          span {
            margin-right: 30px;
          }
        }
      }
      .content-container {
        padding: 20px;
        ul {
          list-style: none;
          padding: 0;
        }
        .change-info {
          display: flex;
          li {
            margin-right: 120px;
          }
        }
        .change-explain {
          li {
            margin-bottom: 15px;
          }
        }
        .influence-module {
          h4 {
            margin: 15px 0;
          }
          .btn-box {
            margin-bottom: 10px;
            display: flex;
          }
        }
        .change-record {
          h4 {
            margin: 15px 0;
          }
          .record-container {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            > li {
              width: 50%;
              margin-bottom: 15px;
              &:nth-child(odd) {
                .ant-collapse {
                  margin-right: 1%;
                  width: 99%;
                }
              }
              &:nth-child(even) {
                .ant-collapse {
                  margin-left: 1%;
                  width: 99%;
                }
              }
            }
          }
        }
        .btn {
          display: flex;
          justify-content: center;
          margin-top: 30px;
          position: fixed;
          bottom: 15px;
          left: 0;
          width: 100%;
          z-index: 1;
          > button {
            min-width: 150px;
            margin: 0 5px;
          }
        }
      }
      .infoTips {
        background: #e6f7ff;
        border: 1px solid #aee1ff;
        border-radius: 4px;
        padding: 5px 10px;
        font-size: 12px;
        color: #888;
      }
    }
  }
}
.line-content {
  .ant-col-8 {
    width: 30%;
    &:first-child {
      width: 40%;
    }
  }
}
.content-container .dept {
  /deep/ .ant-form-item .ant-form-item-label {
    width: 165px;
  }
}
.info-detail {
  background-color: #f6f7f9;
  border: 1px solid #ebebeb;
  padding: 1% 2.5%;
  position: relative;
  margin-bottom: 20px;
  .info-list {
    margin: 0;
    font-size: 16px;
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 15px;
    > li {
      width: 25%;
      height: 25px;
      display: flex;
      align-items: center;
      > img {
        margin-right: 5px;
      }
      .list-title {
        height: unset;
        font-weight: 900;
      }
    }
    .one-row {
      width: 100%;
    }
  }
  .info-content {
    .content-title {
      display: flex;
      align-items: center;
      font-weight: 900;
      img {
        margin-right: 5px;
      }
    }
    .content-box {
      padding: 5px 16px 0;
    }
  }
  .redfont {
    color: #fe6e6c;
    font-weight: bold;
    font-size: 18px;
    &.borderleft::after {
      content: '';
      width: 1px;
      height: 10px;
      color: red;
      border-left: 1px solid #e3e3e3;
      position: absolute;
      left: -40px;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  }
}

.info-list {
  display: flex;
  flex-wrap: wrap;
  border-bottom: 1px dashed #ebebeb;
  > li {
    width: 100%;
    height: 25px;
    display: flex;
    align-items: center;
    > img {
      margin-right: 5px;
    }
    .list-title {
      width: 150px;
      font-weight: 900;
    }
  }
}

/deep/.ant-table-placeholder {
  z-index: unset;
}
.totalExpenses {
  display: flex;
  justify-content: space-between;
  font-weight: bolder;
}
/deep/ .ant-table-body::-webkit-scrollbar-track {
  background-color: #fff;
}
/deep/ .ant-checkbox-disabled + span {
  color: unset;
}
/deep/ div.inner-table.ant-table-wrapper {
  margin: -7px -11px 5px -11px;
  table {
    border: none;
  }
}
.full-modal {
  /deep/ .ant-modal {
    max-width: 100%;
    top: 0 !important;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
/deep/  .full-modal {
  /deep/ .ant-modal {
    top: 0 !important;
  }
}
</style>
